<template>
  <view class="rooms-container">
    <u-pull-refresh 
      @refresh="onRefresh" 
      :status="refreshStatus"
      class="pull-box"
    >
      <u-list
        @scrolltolower="loadMore"
        class="room-list"
      >
        <view v-for="(room, index) in roomList" :key="index" class="room-item">
          <view class="room-header">
            <view class="room-title">{{ room.buildingName + room.name }}</view>
            <view :class="['face-verify-tag', room.faceVerifyStatus == 1 ? 'verified' : 'unverified']">
              {{ room.faceVerifyStatus == 1 ? '已认证' : '未认证' }}
            </view>
          </view>
          
          <view class="room-content">
            <view class="info-row">
              <u-icon name="rmb-circle" color="#ff8c00" size="40"></u-icon>
              <text class="info-label">租金：</text>
              <text class="info-value price">¥{{ room.monthlyRent }}/月</text>
            </view>
            
            <view class="info-row">
              <u-icon name="account" color="#409eff" size="40"></u-icon>
              <text class="info-label">入住人数：</text>
              <text class="info-value">{{ room.residentCount }}人</text>
            </view>
            
            <view class="info-row">
              <u-icon name="calendar" color="#67c23a" size="40"></u-icon>
              <text class="info-label">入住时间：</text>
              <text class="info-value">{{ formatDate(room.validityStart) }} 至 {{ formatDate(room.validityEnd) }}</text>
            </view>
          </view>
          
          <view class="room-footer">
			      <u-button size="mini" @click="goToElectricifyRecord(room.roomId)">用电记录</u-button>
			      <u-button size="mini" @click="goToManageCohabitant(room.checkInId, room.apartmentId)" v-if="room.isMainRenter" style="margin-left: 20rpx;">管理室友</u-button>
			      <u-button size="mini" @click="goToCohabitantDetail(room.renterId)" v-else style="margin-left: 20rpx;">个人信息</u-button>
            <u-button v-if="room.faceVerifyStatus == 0" type="primary" size="mini" @click="goToVerify(room.renterId)" style="margin-left: 20rpx;">去认证</u-button>
          </view>
        </view>
        
        <u-loadmore 
          :status="loadMoreStatus" 
          :load-text="loadMoreText"
          margin-top="20"
          margin-bottom="20"
        />
      </u-list>
    </u-pull-refresh>
  </view>
</template>

<script>
import { roomList } from '@/api/room'

export default {
  name: 'RoomsList',
  data() {
    return {
      roomList: [],
      page: 1,
      pageSize: 10,
      refreshStatus: 'default',
      loadMoreStatus: 'loadmore',
      loadMoreText: {
        loadmore: '上拉加载更多',
        loading: '正在加载...',
        nomore: '没有更多数据了',
      },
      isLoading: false
    }
  },
  onLoad() {
    this.getRoomList()
  },
  onPullDownRefresh() {
  	this.getRoomList()
  },
  methods: {
    onClickLeft() {
      uni.navigateBack()
    },
    async getRoomList(type = 'init') {
      if (this.isLoading) return
      
      this.isLoading = true
      
      try {
        if (type === 'refresh') {
          this.page = 1
          this.roomList = []
          this.loadMoreStatus = 'loadmore'
        }
        
        const res = await roomList({
          page: this.page,
          pageSize: this.pageSize
        })
        
        if (res && res.data) {
          if (type === 'init' || type === 'refresh') {
            this.roomList = res.data || []
          } else {
            this.roomList = [...this.roomList, ...(res.data || [])]
          }
          
          if (!res.data || res.data.length == 0) {
            this.loadMoreText.nomore = '暂无房间，请联系公寓管理员绑定房间'
            this.loadMoreStatus = 'nomore'
          } else if (res.data.length < this.pageSize) {
            this.loadMoreText.nomore = '没有更多数据了'
            this.loadMoreStatus = 'nomore'
          } else {
            this.loadMoreStatus = 'loadmore'
          }
          
          this.page++
        }
      } catch (error) {
        console.error('获取房间列表失败', error)
        uni.showToast({
          title: '获取房间列表失败',
          icon: 'none'
        })
      } finally {
        this.isLoading = false
        if (type === 'refresh') {
          this.refreshStatus = 'success'
          setTimeout(() => {
            this.refreshStatus = 'default'
          }, 1000)
        }
      }
    },
    onRefresh() {
      this.refreshStatus = 'loading'
      this.getRoomList('refresh')
    },
    loadMore() {
      if (this.loadMoreStatus !== 'loadmore') return
      this.loadMoreStatus = 'loading'
      this.getRoomList('loadmore')
    },
    formatDate(timestamp) {
      if (!timestamp) return '未设置'
      const date = new Date(timestamp)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    },
    goToVerify(renterId) {
      // 跳转到人脸认证页面，并传递房间ID
      uni.navigateTo({
        url: `/pages/home/face-verify/index?renterId=${renterId}`
      })
    },
    goToManageCohabitant(checkInId, apartmentId) {
      uni.navigateTo({
        url: `/pages/home/cohabitant/index?checkInId=${checkInId}&apartmentId=${apartmentId}`
      })
    },
    goToCohabitantDetail(renterId) {
      uni.navigateTo({
        url: `/pages/home/cohabitant/detail?renterId=${renterId}`
      })
    },
    goToElectricifyRecord(roomId) {
      uni.navigateTo({
        url: `/pages/home/electricify-record/index?roomId=${roomId}`
      })
    } 
  }
}
</script>

<style lang="scss" scoped>
.rooms-container {
  background-color: #f5f7fa;
  min-height: 100vh;
  padding: 32rpx;
  display: flex;
  flex-direction: column;
}

.pull-box {
  flex: 1;
}

.room-item {
  background-color: #ffffff;
  border-radius: 24rpx;
  margin-bottom: 30rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 24rpx 0 rgba(0, 0, 0, 0.05);
}

.room-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 20rpx;
}

.room-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #303133;
}

.face-verify-tag {
  padding: 8rpx 16rpx;
  border-radius: 8rpx;
  font-size: 24rpx;
}

.verified {
  background-color: #f0f9eb;
  color: #67c23a;
  border: 1px solid #c2e7b0;
}

.unverified {
  background-color: #fef0f0;
  color: #f56c6c;
  border: 1px solid #fbc4c4;
}

.room-content {
  padding: 10rpx 0;
}

.info-row {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
  font-size: 28rpx;
  color: #606266;
}

.info-label {
  margin-left: 10rpx;
}

.info-value {
  color: #303133;
}

.price {
  color: #ff6b00;
  font-weight: bold;
}

.room-footer {
  margin-top: 24rpx;
  display: flex;
  justify-content: flex-end;
}
</style> 